import { useState, useEffect } from "react";

export const useCountdown = ({ seconds, onFinish }) => {
  // 倒计时
  const [countdown, setCountdown] = useState(seconds);
  const [state, setState] = useState("获取验证码");
  const [isCounting, setIsCounting] = useState(false);

  useEffect(() => {
    if (isCounting) {
      if (countdown === 0) {
        setState("重新获取");
        setIsCounting(false);
        onFinish();
      } else {
        const timer = setTimeout(() => {
          setCountdown(countdown - 1);
          setState(`${countdown - 1}s`);
        }, 1000);
        return () => clearTimeout(timer);
      }
    }
  }, [countdown, isCounting, onFinish]);
  const startCountdown = () => {
    setCountdown(seconds);
    setState(`${seconds}s`);
    setIsCounting(true);
  };

  return {
    state,
    startCountdown,
  };
};
